package com.iwunu.gateway.callback;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.config.MqttCofigBean;
import com.iwunu.gateway.service.FLcokMqttReceiveService;
import com.iwunu.iot.common.constant.ClientDataEnum;

public class TopMsgCallback implements MqttCallback,CommandLineRunner  {

	private static Logger logger = LoggerFactory.getLogger(TopMsgCallback.class);
	@Autowired
	private FLcokMqttReceiveService fLcokMqttReceiveService;
	private MqttClient client;
	private MqttConnectOptions options;
	private String[] topic;
	private int[] qos;
	private Map<String, String> topicMap;
	public MqttCofigBean mqttCofigBean;

	public TopMsgCallback() {
	}

	public TopMsgCallback(MqttClient client, MqttConnectOptions options, String[] topic, int[] qos,
			FLcokMqttReceiveService fLcokMqttReceiveService, Map<String, String> topicMap,MqttCofigBean mqttCofigBean) {
		this.client = client;
		this.options = options;
		this.topic = topic;
		this.qos = qos;
		this.fLcokMqttReceiveService = fLcokMqttReceiveService;
		this.topicMap = topicMap;
		this.mqttCofigBean = mqttCofigBean;
	}

	/**
	 ** 断开重连
	 */
	public void connectionLost(Throwable cause) {
        try {
        	client.disconnect();
        	client.close();
            client.connect(options);
//            if (null != client && !client.isConnected()) {
//                this.connect();
//                logger.error("if 尝试重新连接");
//            } else {
//            	client.disconnect();
//                client.connect(options);
//                logger.error("else 尝试建立新连接");
//            }
//            if (client.isConnected()) {//连接成功，跳出连接
//                return;
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
	}

	/**
	 * 接收到消息调用令牌中调用
	 */
	public void deliveryComplete(IMqttDeliveryToken token) {
	}

	public void messageArrived(String topic, MqttMessage message) {
		JSONObject msg = (JSONObject) JSONObject.parse(new String(message.getPayload()));
		try {
			//订阅消息字符
	    	if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.START.getName())) {
			  	fLcokMqttReceiveService.handlerAnswerMqttMessage(topicMap.get(ClientDataEnum.START.getName()), msg);
			}
	    	else 
			if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.CALLBACK.getName())) {
				fLcokMqttReceiveService.handlerCallbackMqttMessage(topicMap.get(ClientDataEnum.ANSWER.getName()), msg);				
			}
			else if (topic.trim().substring(topic.lastIndexOf(".") + 1, topic.length())
					.equals(ClientDataEnum.FM226.getName())) {
				fLcokMqttReceiveService.handlerCallbackMqttMessage(topicMap.get(ClientDataEnum.FEATURE.getName()), msg);
			}
			else if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.GENERAL.getName())) {
				fLcokMqttReceiveService.handlerGeneralMqttMessage(topicMap.get(ClientDataEnum.GENERAL.getName()), msg);			
			}
			else if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.SUCCESS.getName())) {
				fLcokMqttReceiveService.handlerSuccessMqttMessage(topicMap.get(ClientDataEnum.GENERAL.getName()), msg);
			}
			else if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.PASSWORD.getName())) {
				fLcokMqttReceiveService.handlerPasswordMqttMessage(topicMap.get(ClientDataEnum.GENERAL.getName()), msg);
			}
			else if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.CARD.getName())) {
				fLcokMqttReceiveService.handlerCardMqttMessage(topicMap.get(ClientDataEnum.GENERAL.getName()), msg);
			}
			else if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.FINGER.getName())) {
				fLcokMqttReceiveService.handlerFingerMqttMessage(topicMap.get(ClientDataEnum.GENERAL.getName()), msg);
			}
			else if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.DELIMAGE.getName())) {
				fLcokMqttReceiveService.handlerDelImageMqttMessage(topicMap.get(ClientDataEnum.GENERAL.getName()), msg);
			}
			else if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.REPORT.getName())) {
				fLcokMqttReceiveService.handlerReportMqttMessage(topicMap.get(ClientDataEnum.REPORT.getName()), msg);
			}
//			else if(topic.trim().substring(topic.lastIndexOf(".")+1, topic.length()).equals(ClientDataEnum.OTHER.getName())) {
//				fLcokMqttReceiveService.handlerOtherMqttMessage(topicMap.get(ClientDataEnum.OTHER.getName()), msg);
//			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		
	}


	// 对象转化为字节码
	public byte[] getBytesFromObject(Serializable obj) throws Exception {
		if (obj == null) {
			return null;
		}
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		ObjectOutputStream oo = new ObjectOutputStream(bo);
		oo.writeObject(obj);
		return bo.toByteArray();
	}
	 /**
     *  用来连接服务器
     */
    private void connect() throws Exception{
        client = new MqttClient(mqttCofigBean.getHostUrl(),mqttCofigBean.getSclientId(), new MemoryPersistence());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(mqttCofigBean.getUsername());
        options.setPassword(mqttCofigBean.getPassword().toCharArray());
        //是否清除session
        options.setCleanSession(false);
        // 设置超时时间
        options.setConnectionTimeout(mqttCofigBean.getCompletionTimeout());
        options.setAutomaticReconnect(true);
        // 设置会话心跳时间
        options.setKeepAliveInterval(mqttCofigBean.getKeepalive());
        
        try {
            String[] msgtopic = mqttCofigBean.getReceiveTopic().split(",");
            String[] sendtopic = mqttCofigBean.getSendTopic().split(",");
            Map<String, String> topicMap = new HashMap<String, String>();
            //订阅消息
            int[] qos = new int[msgtopic.length];
            for (int i = 0; i < msgtopic.length; i++) {
                qos[i]=0;
            }
            if(sendtopic!=null&&sendtopic.length>0) {
            	
            	for(int i=0;i<sendtopic.length;i++) {
            		String key = sendtopic[i].substring(sendtopic[i].lastIndexOf(".")+1, sendtopic[i].length());
            		topicMap.put(key, sendtopic[i]);
            	}
            }
            
            client.setCallback(new TopMsgCallback(client,options,sendtopic,qos,fLcokMqttReceiveService,topicMap,mqttCofigBean));
            client.connect(options);
            client.subscribe(msgtopic,qos);
            logger.info("MQTT连接成功:"+mqttCofigBean.getSclientId()+":"+client);
        } catch (Exception e) {
            logger.error("MQTT连接异常："+e);
        }
    }

	@Override
	public void run(String... args) throws Exception {
		logger.info("初始化启动MQTT连接");
		 this.connect();
		
	}
}
